// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();//初始化云数据库
const playlistCollect = db.collection('playlist');
var rp = require('request-promise');
const URL = 'https://music.kele8.cn/personalized'
const MAX_LIMIT = 100;
// 云函数入口函数
exports.main = async (event, context) => {
  // const  list = await playlistCollect.get();
  const playlist = await rp(URL).then(res=>{
    return JSON.parse(res).result
   })

  const countResult = await playlistCollect.count();//获取总条数，返回的是对象
  const total = countResult.total;
  const batchTimes = Math.ceil(total / MAX_LIMIT);
  const task = [];
  for(let i = 0;i<batchTimes;i++){
    let promise = await playlistCollect.skip(i*MAX_LIMIT).limit(MAX_LIMIT).get();
    task.push(promise)
  }
 let list = {
   data:[]
 }
 if(task.length>0){
    list = (await Promise.all(task)).reduce((acc,cur)=>{
     return{
       data:acc.data.concat(cur.data)
     }
   })
 }

  let newData = [];
  // console.log('playlist----\n',playlist,'listdata---\n',list.data);
   //歌单去重
   for(let i = 0;i<playlist.length;i++){
     let flag = true
     for(var j = 0;j<list.data.length;j++){
        if(playlist[i].id === list.data[j].id){
            flag = false
            break
        }
     }
     if(flag){
       newData.push(playlist[i])
     }
   }
 
  if(newData.length>0){
    for(let i = 0;i<newData.length;i++){
      await playlistCollect.add({
        data:{
          ...newData[i],
          createtime:db.serverDate()
        }
      }).then((res)=>{
        console.log('插入成功');
      }).catch((err)=>{
        console.log('插入失败');
      })
    }
  }
  return newData.length;
}